package com.hg.design;

import org.springframework.lang.NonNull;

import java.util.ArrayList;
import java.util.Collection;

public class MaxSizeArrayList extends ArrayList {
    private final long mMaxSize;

    public MaxSizeArrayList(int maxSize) {
        this.mMaxSize = maxSize;
    }

    @Override
    public synchronized boolean add(Object o) {
        if (size() == mMaxSize) {//大于最大长度时，移除第一个
            remove(0);
        }
        return super.add(o);
    }

    @Override
    public synchronized Object remove(int index) {
        return super.remove(index);
    }

    @Override
    public synchronized boolean addAll(@NonNull Collection c) {
        Object[] objects = c.toArray();
        for (Object o : objects) {
            add(o);
        }
        return size() == mMaxSize;
    }

    @Deprecated
    @Override
    public synchronized void add(int index, Object element) {
        //可自定义逻辑
    }

    @Deprecated
    @Override
    public synchronized boolean addAll(int index, @NonNull Collection c) {
        //可自定义逻辑
        return false;
    }
}
